package com.xuef.security.config;

import com.xuef.security.browser.BlogAuthenticationSucHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * Created by moveb on 2018/5/20.
 */
@EnableGlobalMethodSecurity(prePostEnabled = true) // 启用方法安全设置
@EnableWebSecurity
@Component
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private BlogAuthenticationSucHandler blogAuthenticationSucHandler;

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/css/**", "/js/**", "/fonts/**", "/index").permitAll()
                .antMatchers("/admins/**").hasRole("ADMIN")
                // 登录用户才可以新增博客
                .antMatchers("/space/*/blogs/edit").hasRole("USER")
                .and()
            .formLogin()
                // 指定登录页,此处指定/authentication/require 来处理登录
                .loginPage("/authentication/require").permitAll()
                // 告诉UsernamePasswordAuthenticationFilter 处理/authentication/form （POST）
                // 这个请求。默认是处理 /login （POST）
                .loginProcessingUrl("/login")
                //.loginProcessingUrl("/authentication/form")
                // 登录失败后处理的url
                // 登录成功后调用
                .successHandler(blogAuthenticationSucHandler)
                .failureUrl("/login-error")
                //.failureHandler(blogAuthenticationFailureHandler)
                .and()
            .csrf().disable(); // 关闭spring security 的防止跨站攻击
    }
}
